package com.huaxinkaiye.utils;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 实现拍照的功能，继承此类的皆有拍照的功能 注入PopupMenu事件
 * 
 * @author imac
 */
public abstract class PhotoImplActivity extends Activity implements
		com.huaxinkaiye.utils.PopupMenu.CallBack {

	// 弹出框
	private PopupMenu popupMenu;

	// 保存图片
	public static List<Bitmap> bitmaps = new ArrayList<Bitmap>();
	// public static List<Bitmap> bmp = new ArrayList<Bitmap>();
	public ArrayList<String> drr = new ArrayList<String>(); // 多张图片
	public CallBack callBack;

	public boolean isEnableCut = false;
	public String type;

	private static final int TAKE_PICTURE = 0;
	private static final int RESULT_LOAD_IMAGE = 1;
	private static final int CUT_PHOTO_REQUEST_CODE = 2;
	private static final int SELECTIMG_SEARCH = 3;
	private String path = "";
	private Uri photoUri;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	public void setEnableCut(boolean isEnable) {
		this.isEnableCut = isEnable;
	}

	/**
	 * 在子类中调用该方法启动拍照功能
	 * 
	 * @param parent
	 */
	protected void showPopupMenu(View parent, boolean isEnableCut, String type) {
		this.type = type;
		popupMenu = new PopupMenu(this, parent);
		popupMenu.setCallBack(this);
		setEnableCut(isEnableCut);
	}

	@Override
	public void OnPhotoClickListener() {
		photo();
	}

	@Override
	public void OnPickPhotoListener() {
		// 相册
		Intent i = new Intent(Intent.ACTION_PICK,
				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(i, RESULT_LOAD_IMAGE);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case TAKE_PICTURE:
			if (resultCode == -1) {// 拍照
				drr.add(photoUri.toString());
				doCallBack(photoUri.toString());
				if (isEnableCut) {
					startPhotoZoom(photoUri);
				} else {
					startPhotoZoomNoC(photoUri);
				}
			}
			break;
		case RESULT_LOAD_IMAGE:
			if (resultCode == RESULT_OK && null != data) {// 相册返回
				Uri uri = data.getData();
				drr.add(uri.toString());
				Log.e("uri.toString()_xiangche", uri.toString());
				doCallBack(uri.toString());
				if (uri != null) {
					if (isEnableCut) {
						startPhotoZoom(uri);
					} else {
						startPhotoZoomNo(uri);
					}
				}
			}
			break;
		case CUT_PHOTO_REQUEST_CODE:
			if (resultCode == RESULT_OK && null != data) {// 裁剪返回
				// 根据路径获取bitmap，并保存再bitmaps中
				Bitmap bitmap = null;
				Log.e("drr.get(drr.size() - 1)", drr.get(drr.size() - 1));
				try {
					FileInputStream fis = new FileInputStream(drr.get(drr
							.size() - 1));
					bitmap = BitmapFactory.decodeStream(fis); // /把流转化为Bitmap图片
					fis.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				doAfterZoom(bitmap);
			}
			break;
		}
	}

	private void photo() {
		try {
			Intent openCameraIntent = new Intent(
					MediaStore.ACTION_IMAGE_CAPTURE);
			// 获得SD卡状态
			String sdcardState = Environment.getExternalStorageState();
			String sdcardPathDir = android.os.Environment
					.getExternalStorageDirectory().getPath() + "/tempImage/";
			File file = null;
			// 如果SD卡已经装好
			if (Environment.MEDIA_MOUNTED.equals(sdcardState)) {
				// 有sd卡，是否有myImage文件夹
				File fileDir = new File(sdcardPathDir);
				if (!fileDir.exists()) {
					fileDir.mkdirs();
				}
				// 是否有headImg文件
				file = new File(sdcardPathDir + System.currentTimeMillis()
						+ ".JPEG");
			}
			if (file != null) {
				path = file.getPath();
				photoUri = Uri.fromFile(file);
				openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
				startActivityForResult(openCameraIntent, TAKE_PICTURE);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void startPhotoZoom(Uri uri) {
		// 获取系统时间 然后将裁剪后的图片保存至指定的文件夹
		SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
		String address = sDateFormat.format(new java.util.Date());
		if (!FileUtils.isFileExist("")) {
			try {
				FileUtils.createSDDir("");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		drr.add(FileUtils.SDPATH + address + ".JPEG");
		Log.e("path0", uri.toString());
		Log.e("path1", FileUtils.SDPATH);
		File file = new File(FileUtils.SDPATH + address + ".JPEG");
		// Uri imageUri = Uri.parse("file:///sdcard/formats/" + address +
		// ".JPEG");
		Uri imageUri = Uri.fromFile(file);
		Log.e("path2", imageUri.toString());
		final Intent intent = new Intent("com.android.camera.action.CROP");
		// 照片URL地址
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		if (type.equals("jiandang")) {
			intent.putExtra("outputX", 300);
			intent.putExtra("outputY", 250);
			intent.putExtra("scale", false);
		} else {
			intent.putExtra("outputX", 1088);
			intent.putExtra("outputY", 612);
			intent.putExtra("scale", false);
		}
		// 输出路径
		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		// 输出格式
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		// 不启用人脸识别
		intent.putExtra("noFaceDetection", false);
		intent.putExtra("return-data", false);
		startActivityForResult(intent, CUT_PHOTO_REQUEST_CODE);
	}

	private void startPhotoZoomNoC(Uri uri) {
		Log.e("img_path===", "-----" + uri.toString().substring(7));
		Bitmap bitmap = null;
		try {
			FileInputStream fis = new FileInputStream(uri.toString().substring(
					7));
			bitmap = BitmapEdit.createFramedPhoto(1088,612,
					BitmapFactory.decodeStream(fis), 0); // /把流转化为Bitmap图片
			fis.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		doAfterZoom(bitmap);
	}

	public void startPhotoZoomNo(Uri uri) {
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
		int actual_image_column_index = actualimagecursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		actualimagecursor.moveToFirst();
		String img_path = actualimagecursor
				.getString(actual_image_column_index);
		Log.e("img_path===", img_path);
		// File file = new File(img_path);
		// Uri fileUri = Uri.fromFile(file);
		Bitmap bitmap = null;
		Log.e("drr.get(drr.size() - 1)no", drr.get(drr.size() - 1));
		try {
			FileInputStream fis = new FileInputStream(img_path);
			bitmap = BitmapEdit.createFramedPhoto(1088,612,
					BitmapFactory.decodeStream(fis), 0); // /把流转化为Bitmap图片
			fis.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		doAfterZoom(bitmap);
	};

	@Override
	protected void onDestroy() {
		FileUtils.deleteDir(FileUtils.SDPATH);
		// 清理图片缓存
		for (int i = 0; i < bitmaps.size(); i++) {
			bitmaps.get(i).recycle();
		}
		bitmaps.clear();
		drr.clear();
		super.onDestroy();
	}

	public abstract void doAfterZoom(Bitmap bitmap);

	public void doCallBack(String url) {
		if (this.callBack != null) {
			callBack.done(url);
		}
	}

	public void setCallBack(CallBack callBack) {
		this.callBack = callBack;
	}

	public interface CallBack {
		void done(String url);
	}
}
